#include "SwitchRailDriver.h"
#include "Timer.h"

/* CONSTRUCTOR */
SwitchRailDriver::SwitchRailDriver(SwitchRailDriverData switchRailDriverData)
{
  m_id = switchRailDriverData.getId();
  m_coilPortGoStraightOn = switchRailDriverData.getCoilPortGoStraightOn();
  m_coilPortChangeDirection = switchRailDriverData.getCoilPortChangeDirection();
  
  pinMode(m_coilPortGoStraightOn, OUTPUT);    // Configure Port in output state
  pinMode(m_coilPortChangeDirection, OUTPUT);
  switchOffAllCoils();  // Coil ports are LOW
}


/* METHODES */

/**
* \brief Verify if switch position has changed and update its state
* \param eventId
* \return none
*/
void SwitchRailDriver::timerCallbackFunction(int eventId)
{
  if(eventId == m_timeEventId)
  {
    switchOffAllCoils();
  }
  else
  {
     /* Wrong event */ 
  }
}

/**
* \brief Train goes straight on. Power on corresponding coil.
* \param none
* \return none
*/
void SwitchRailDriver::goStraightOn()
{
  //m_coilGoStraightOnState = HIGH;
  digitalWrite(m_coilPortGoStraightOn, HIGH);
  
  Timer* t = Timer::getTimer();
  m_timeEventId = t->after(15, this);  // ON during 15 ms
}

/**
* \brief Train goes in other direction. Power on corresponding coil.
* \param none
* \return none
*/
void SwitchRailDriver::changeDirection()
{
  //m_coilChangeDirectionState = HIGH;
  digitalWrite(m_coilPortChangeDirection, HIGH);
  Timer* t = Timer::getTimer();
  m_timeEventId = t->after(15, this);  // ON during 15 ms
}

/**
* \brief Shut down all coils power.
* \param none
* \return none
*/
void SwitchRailDriver::switchOffAllCoils()
{
  digitalWrite(m_coilPortGoStraightOn, LOW);
  digitalWrite(m_coilPortChangeDirection, LOW);
}

/**
* \brief Get switch rail driver Id
* \param none
* \return id
*/
byte SwitchRailDriver::getId()
{
  return m_id;
}
